/**
 * Angularjs环境下分页
 * name: tm.pagination
 * Version: 1.0.0
 */
angular.module('tm.pagination', []).directive('tmPagination',[function(){
    return {
        restrict: 'EA',
        template: '<div class="page-list">' +
            '<ul class="pagination" ng-show="conf.totalItems > 0">' +
            '<li ng-class="{disabled: conf.currentPage == 1}" ng-click="prevPage()"><span>&laquo;</span></li>' +
            '<li ng-repeat="item in pageList track by $index" ng-class="{active: item == conf.currentPage, separate: item == \'...\'}" ' +
            'ng-click="changeCurrentPage(item)">' +
            '<span>{{ item }}</span>' +
            '</li>' +
            '<li ng-class="{disabled: conf.currentPage == conf.numberOfPages}" ng-click="nextPage()"><span>&raquo;</span></li>' +
            '</ul>' +
            '<div class="page-total" ng-show="conf.totalItems > 0">' +
            '第<input type="text" ng-model="jumpPageNum"  ng-keyup="jumpToPage($event)"/>页 ' +
            '每页<select ng-model="conf.itemsPerPage" ng-options="option for option in conf.perPageOptions " ng-change="changeItemsPerPage()"></select>' +
            '/共<strong>{{ conf.totalItems }}</strong>条' +
            '</div>' +
            '</div>',
        replace: true,
        scope: {
            conf: '='
        },
        link: function(scope, element, attrs){
        	var tableID = angular.element(".table_store").attr("id");
            // 变更当前页
            scope.changeCurrentPage = function(item){
                if(item == '...'){
                    return;
                }else{
                    scope.conf.currentPage = item;
                }
                refresh();
            };

            // 定义分页的长度必须为奇数 (default:9)
            scope.conf.pagesLength = parseInt(scope.conf.pagesLength) ? parseInt(scope.conf.pagesLength) : 9 ;
            if(scope.conf.pagesLength % 2 === 0){
                // 如果不是奇数的时候处理一下
                scope.conf.pagesLength = scope.conf.pagesLength -1;
            }

            // conf.erPageOptions
            if(!scope.conf.perPageOptions){
                scope.conf.perPageOptions = [10, 15, 20, 30, 50];
            }
            
            function initPageList(){
            	scope.conf.numberOfPages = Math.ceil(scope.conf.totalItems/scope.conf.itemsPerPage);
            	scope.pageList = [];
                if(scope.conf.numberOfPages <= scope.conf.pagesLength){
                    // 判断总页数如果小于等于分页的长度，若小于则直接显示
                    for(i =1; i <= scope.conf.numberOfPages; i++){
                        scope.pageList.push(i);
                    }
                }else{
                    // 总页数大于分页长度（此时分为三种情况：1.左边没有...2.右边没有...3.左右都有...）
                    // 计算中心偏移量
                    var offset = (scope.conf.pagesLength - 1)/2;
                    if(scope.conf.currentPage <= offset){
                        // 左边没有...
                        for(i =1; i <= offset +1; i++){
                            scope.pageList.push(i);
                        }
                        scope.pageList.push('...');
                        scope.pageList.push(scope.conf.numberOfPages);
                    }else if(scope.conf.currentPage > scope.conf.numberOfPages - offset){
                        scope.pageList.push(1);
                        scope.pageList.push('...');
                        for(i = offset + 1; i >= 1; i--){
                            scope.pageList.push(scope.conf.numberOfPages - i);
                        }
                        scope.pageList.push(scope.conf.numberOfPages);
                    }else{
                        // 最后一种情况，两边都有...
                        scope.pageList.push(1);
                        scope.pageList.push('...');

                        for(i = Math.ceil(offset/2) ; i >= 1; i--){
                            scope.pageList.push(scope.conf.currentPage - i);
                        }
                        scope.pageList.push(scope.conf.currentPage);
                        for(i = 1; i <= offset/2; i++){
                            scope.pageList.push(scope.conf.currentPage + i);
                        }

                        scope.pageList.push('...');
                        scope.pageList.push(scope.conf.numberOfPages);
                    }
                }
            }

            // pageList数组
            function getPagination(){
                // conf.currentPage
                scope.conf.currentPage = parseInt(scope.conf.currentPage) ? parseInt(scope.conf.currentPage) : 1;
                // conf.totalItems
                scope.conf.totalItems = parseInt(scope.conf.totalItems);

                // conf.itemsPerPage (default:15)
                // 先判断一下本地存储中有没有这个值
                if(scope.conf.rememberPerPage){
                    if(!parseInt(localStorage[scope.conf.rememberPerPage])){
                        localStorage[scope.conf.rememberPerPage] = parseInt(scope.conf.itemsPerPage) ? parseInt(scope.conf.itemsPerPage) : 15;
                    }

                    scope.conf.itemsPerPage = parseInt(localStorage[scope.conf.rememberPerPage]);

                }else{
                    scope.conf.itemsPerPage = parseInt(scope.conf.itemsPerPage) ? parseInt(scope.conf.itemsPerPage) : 15;
                }
                
                
                	 //保存本地存储中的页码页数
                localStorage[tableID+"_Page"]=scope.conf.currentPage;
				localStorage[tableID+"_Size"]= scope.conf.itemsPerPage;

                // numberOfPages
                scope.conf.numberOfPages = Math.ceil(scope.conf.totalItems/scope.conf.itemsPerPage);

                // judge currentPage > scope.numberOfPages
                if(scope.conf.currentPage < 1){
                    scope.conf.currentPage = 1;
                }

                if(scope.conf.currentPage > scope.conf.numberOfPages){
                    scope.conf.currentPage = scope.conf.numberOfPages;
                }

                // jumpPageNum
                scope.jumpPageNum = scope.conf.currentPage;

                // 如果itemsPerPage在不在perPageOptions数组中，就把itemsPerPage加入这个数组中
                var perPageOptionsLength = scope.conf.perPageOptions.length;
                // 定义状态
                var perPageOptionsStatus;
                for(var i = 0; i < perPageOptionsLength; i++){
                    if(scope.conf.perPageOptions[i] == scope.conf.itemsPerPage){
                        perPageOptionsStatus = true;
                    }
                }
                // 如果itemsPerPage在不在perPageOptions数组中，就把itemsPerPage加入这个数组中
                if(!perPageOptionsStatus){
                    scope.conf.perPageOptions.push(scope.conf.itemsPerPage);
                }

                // 对选项进行sort
                scope.conf.perPageOptions.sort(function(a, b){return a-b});

                initPageList();

                if(scope.conf.onChange){
                    scope.conf.onChange();
                }
                scope.$parent.conf = scope.conf;
            }

            // prevPage
            scope.prevPage = function(){
                if(scope.conf.currentPage > 1){
                    scope.conf.currentPage -= 1;
                }
                refresh();
            };
            // nextPage
            scope.nextPage = function(){
                if(scope.conf.currentPage < scope.conf.numberOfPages){
                    scope.conf.currentPage += 1;
                }
                refresh();
            };

            // 跳转页
            scope.jumpToPage = function(event){
            	if (!scope.jumpPageNum||event.keyCode != 13){
                    return;
                }
            	if(typeof scope.jumpPageNum=='string')
            		 scope.jumpPageNum = scope.jumpPageNum.replace(/[^0-9]/g,'');
                if(scope.jumpPageNum !== ''){
                    scope.conf.currentPage = scope.jumpPageNum;
                }
                refresh();
            };
            
            // 修改每页显示的条数
            scope.changeItemsPerPage = function(){
                // 清除本地存储的值方便重新设置
                if(scope.conf.rememberPerPage){
                    localStorage.removeItem(scope.conf.rememberPerPage);
                }
                refresh();
            };
            function refresh(){
            	getPagination();
            	scope.conf.refresh = scope.conf.refresh?false:true;
            };

            scope.$watch("conf.currentPage + scope.conf.itemsPerPage",getPagination);
            scope.$watch("conf.totalItems",initPageList);
        }
    };
}]);

angular.module('tm.headselected', []).directive('tmHeadselected',[function(){
    return {
        restrict: 'EA',
        template: '<select class="hide column_select"  size=8 ><option  ng-click="changeValue($event.target)"   value="">全部</option><option ng-repeat="v in values" ng-click="changeValue($event.target)"   value="{{v}}">{{v}}</option></select><span ng-click="openSelect($event.target)" class="open_select">▼</span>',
        replace: false,
        link: function(scope, element, attrs){
        	 scope.values=[];
        	 var key = attrs.key;
        	 scope.key = key;
        	 var data =attrs.data;
	         scope.openSelect = function(element){
	        	 var ele = angular.element(element);
	        	 angular.element(".column_select").addClass("hide");
	        	 clasz = ele.siblings("select").attr("class");
	        	 var select =  ele.siblings("select");
	        	 select.toggleClass("hide");
	         };
	         scope.changeValue = function(option){
	        	 angular.element(".column_select").addClass("hide");
	        	 scope.params={};
	        	 if(option.value!="")
	        		 scope.params[key]=option.value;
	        	 scope.conf.changed=!scope.conf.changed;
	         };
	        
        	 scope.$watch(data,function(){
        		 var datas = scope[data];
        		 for(var v in datas){
        			 var value = datas[v][key];
        			 if(scope.values.indexOf(value) === -1) {
        				 scope.values.push(value);
        			 }
        		 }
             });
        	
        }
    };
}]);

angular.module('tm.headshow', []).directive('headshow',[function(){
    return {
        restrict: 'EA',
        template: '<div class="col_show_list"><i class="fa fa-list" ng-click="toggleColSelect()"></i><ul>'+
        	'<li ng-repeat="col in lis"><input type="checkbox" index="{{$index + 1 }}"  ng-click="updateChecked($event.target)" ng-checked="isChecked(\'{{col.col}}\')" value="{{col.col}}"  >{{col.name}}</li></ul></div>',
        replace: false,
        
        link: function(scope, element, attrs){
        	var store_key= $(".table_store").attr("id")+"_hides";
        	scope.toggleColSelect = function(option){
        	 	$(".col_show_list ul").toggle();
	        };
	        scope.updateChecked = function(target){
	        	var flag = target.checked;
	        	var value = target.value;
	        	if(!flag){
	        		if(!scope.cols.contains(value))
	        			scope.cols.push(value);
	        	}else
	        		scope.cols.remove(value);
	        	
	        	localStorage[store_key]=JSON.stringify(scope.cols);
	        	if(scope.setCols){
	        		scope.setCols($("#dis_col th[column='"+value+"']").attr("col_index"),flag);
	        	}
	        	
	        };
	        scope.cols = [];
	        if(localStorage[store_key]){
	        	scope.cols =$.parseJSON(localStorage[store_key]);
        	}
	        scope.isChecked = function(column){
	        	return !scope.cols.contains(column);
	        };
	        scope.lis = [];
	        $.each($(".table_store thead tr th"),function(i,n){
	        	var column = $(n).attr("column");
	        	if(column!=''&&column!=undefined){
	        		var name = $(n).text();
			 		var col = {};
			 		col.name=name;
			 		col.col= column;
			 		scope.lis.push(col);
	        	}
	        });
        }
    };
}]);
